package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"novel-mng-sys/cache"
	"novel-mng-sys/models"
	"strconv"
	"time"
)

func NovelList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "10"))
	offset := (page - 1) * size

	var novelList []models.Novel

	//查询redis中是否有数据
	redis_list_key := "list_page_" + strconv.Itoa(page)
	cacheJson, _ := cache.Rdb.Get(cache.Ctx, redis_list_key).Result()
	if cacheJson == "" {

		//从mysql读取数据
		models.DB.Offset(offset).Limit(size).Find(&novelList).Debug()

		//设置到redis缓存中
		jsonData, _ := json.Marshal(novelList)
		cache.Rdb.Set(cache.Ctx, redis_list_key, jsonData, time.Hour*2)

	} else {

		//redis获取数据
		json.Unmarshal([]byte(cacheJson), &novelList)
	}

	var total int64
	models.DB.Model(&models.Novel{}).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"data":  novelList,
		"total": total,
		"msg":   "成功",
	})
	return
}

func NovelDetail(c *gin.Context) {
	id := c.Query("id")

	var novel models.Novel

	redis_list_key := "detail_" + id
	cacheJson, _ := cache.Rdb.Get(cache.Ctx, redis_list_key).Result()
	if cacheJson == "" {

		//从mysql读取数据
		models.DB.Where("id = ?", id).First(&novel)

		//设置到redis缓存中
		jsonData, _ := json.Marshal(novel)
		cache.Rdb.Set(cache.Ctx, redis_list_key, jsonData, time.Hour*2)

	} else {

		//redis获取数据
		json.Unmarshal([]byte(cacheJson), &novel)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"data": novel,
		"msg":  "详情",
	})
	return
}
